<template>
  <h2>监听ref的变化：</h2>
  <div>
    <h2>智能机器人</h2>
    <div>
      <input type="text" v-model="question" placeholder="请输入问题">
    </div>
    <div v-if="loading">正在加载中...</div>
    <div v-else>{{ answer }}</div>
  </div>
  <hr>

  <h2>监听计算属性</h2>
  <div>
    <input type="text" v-model="firstName" placeholder="first name">
  </div>
  <div>
    <input type="text" v-model="lastName" placeholder="first name">
  </div>
  <p>{{ fullName }}</p>
  <hr>

  <h2>监听响应式对象</h2>
  <div>
    <div>
      <input type="text" v-model="user.name" placeholder="name" />
    </div>
    <div>
      <input type="text" v-model="user.age" placeholder="age" />
    </div>
    <p>用户信息：{{ user.name }} - {{ user.age }}</p>
  </div>
  <hr>

  <h2>监听函数</h2>
  <div>
    <input type="number" v-model="count" />
    <!-- <p>是否为偶数？{{ isEven() }}</p> -->
    <div>count2: {{ count2 }}</div>
    <button @click="count2++">count2+1</button>
  </div>
  <hr>

  <h2>监听多个数据源所组成的数组</h2>
  <div>
    <div>
      <input type="text" v-model="title" />
    </div>
    <div>
      <textarea v-model="description" cols="30" rows="10"></textarea>
    </div>
  </div>
  <hr>

  <h2>reactive深层次监听</h2>
  <div>
    <p>任务列表</p>
    <ul>
      <li v-for="(task, index) in tasks.list" :key="task.id">
        {{ task.title }} - {{ task.completed ? '已完成' : '未完成' }}
        <button @click="task.completed = !task.completed">切换状态</button>
      </li>
    </ul>
  </div>
  <hr>

  <h2>如果监听的是reactive对象，不能直接监听响应式对象的属性值</h2>
  <button @click="obj.count++">改变obj.count</button>
  <hr>


  <h2>watch的第三个参数,监听的是一个返回对象的computed，需要加上deep：true</h2>
  <div>
    <div v-for="task in tasks1" :key="task.id" @click="selectTask(task)">
      {{ task.title }} ({{ task.completed ? 'Completed' : 'Pending' }})
    </div>
    <hr />
    <div v-if="selectedTask">
      <h3>Edit Task</h3>
      <input v-model="selectedTask.title" placeholder="Edit title" />
      <label>
        <input type="checkbox" v-model="selectedTask.completed" />
        Completed
      </label>
    </div>
  </div>







</template>

<script setup>
  import { ref, watch, computed, reactive } from "vue";
  const question = ref('')   // 存储用户输入的问题，以 ？ 结束
  const loading = ref(false)  //是否正在加载
  const answer = ref('')

  //监听question的ref
  watch(question, async (newValue, oldValue) => {
    if (newValue.includes('?')) {
      //准备发起请求
      loading.value = true
      answer.value = '思考中。。。'
      try {
        const res = await fetch('https://yesno.wtf/api')
        const result = await res.json()
        answer.value = result.answer
      } catch (error) {
        answer.value = '抱歉，我无法回答您的问题'
      } finally {
        loading.value = false
      }
    }
  })

  const firstName = ref('John')
  const lastName = ref('Doe')
  const fullName = computed(() => `${firstName.value} ${lastName.value}`)
  ///监听computed
  watch(fullName, (newValue) => {
    console.log(`计算属性new值:${newValue}`);
  })

  const user = reactive({
    name: 'John',
    age: 18
  })
  //监听reactive响应式对象变化
  watch(user, () => {
    console.log('触发了reactive的侦听器回调函数')
  })


  const count = ref(0)
  const count2 = ref(0)
  function isEven() {
    console.log('isEvent 函数被重新执行了')
    if (count2.value === 5) {
      return 'this is a test'
    }
    return count.value % 2 === 0
  }
  //这里监听的是函数返回值的结果
  //如果函数的返回值发生变化，才会触发监听器的回调函数
  watch(isEven, (newValue, oldValue) => {
    console.log('触发了侦听器回调函数')
  })

  const title = ref('')
  const description = ref('')
  // 这里侦听的是多个数据源所组成的数组
  // 数组里面任何一个数据发生变化，都会触发回调函数
  watch([title, description], (newValue) => {
    console.log('多数据侦听器的回调函数执行了')
  })


  const tasks = reactive({
    list: [
      { id: 1, title: 'Task 1', completed: false },
      { id: 2, title: 'Task 2', completed: true }
    ]
  })
  watch(tasks, (newValue) => {
    console.log('深层次监听器触发了');
  })

  /* 另外补充一个点，当侦听的是 reactive 对象的时候，不能直接侦听响应式对象的属性值： */
  const obj = reactive({ count: 0 })
  watch(() => obj.count, (newValue) => {
    console.log(`count is: ${newValue}`)
  }, { immediate: true })


  const tasks1 = reactive([
    { id: 1, title: 'Learn Vue', completed: false },
    { id: 2, title: 'Read Documentation', completed: false },
    { id: 3, title: 'Build Something Awesome', completed: false }
  ])

  const selectedId = reactive({ id: null })

  // 这是一个计算属性
  const selectedTask = computed(() => {
    return tasks1.find((task) => task.id === selectedId.id)
  })

  // 侦听的是一个 Getter 函数
  // 该 Getter 函数返回计算属性的值
  watch(
    selectedTask,
    (newValue) => {
      console.log('Task details changed', newValue)
    },
    { deep: true }
  )

  function selectTask(task) {
    selectedId.id = task.id
  }




</script>

<style lang="scss" scoped></style>